package com.leilbase.mspring.bean;

import com.leilbase.mspring.web.mvc.Controller;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class BeanFactory {

    private static Map<Class<?>, Object> beanMap = new ConcurrentHashMap<>();

    public static Object getBean(Class<?> cls) {
        return beanMap.get(cls);
    }

    public static void initBeans(List<Class<?>> classList) throws Exception {
        List<Class<?>> classes = new ArrayList<>(classList);
        while (classes.size() != 0) {
            int remainSize = classes.size();
            for (int i = 0; i < classes.size(); i++) {
                if (finishCreate(classes.get(i))) {
                    classes.remove(i);
                    i--;
                }
            }
            if (classes.size() == remainSize) {
                throw new Exception("cycle dependency");
            }
        }
    }

    public static boolean finishCreate(Class<?> cls) throws IllegalAccessException, InstantiationException {

        if (cls.isAnnotationPresent(Bean.class) || cls.isAnnotationPresent(Controller.class)) {
            // 创建bean
            Object bean = cls.newInstance();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    // 拿到属性的类型
                    Class<?> fieldClass = field.getType();
                    Object fieldObj = BeanFactory.getBean(fieldClass);
                    if (fieldObj == null) {
                        return false;
                    }
                    // 如果成员变量为私有（private）的话，需要调用此方法
                    field.setAccessible(true);
                    field.set(bean, fieldObj);
                }
            }
            BeanFactory.beanMap.put(cls, bean);
            return true;
        } else {
            return true;
        }

    }

}
